package cn.tedu.weibo.controller;

import cn.tedu.weibo.mapper.UserMapper;
import cn.tedu.weibo.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class UserController {

    @Autowired
    UserMapper mapper;

    /**
     * 查找用户是否存在
     * @param username
     * @return
     */
    @RequestMapping("/check")
    public int check(String username) {
        User user = mapper.selectByUsername(username);
        //判断是否在数据库中查找到数据，有则代表用户存在
        if (user != null) {
            return 1;
        }
        return 2;
    }

    /**
     * 注册用户
     * @param user
     * @return
     */
    @RequestMapping("/reg")
    public int reg(User user) {
        User u = mapper.selectByUsername(user.getUsername());
        //查询是否有相同用户名
        if (u != null) {
            return 2;
        }
        //写入用户名
        mapper.insert(user);
        return 1;
    }

    @RequestMapping("/login")
    public int login(User user, HttpSession session){
        User u = mapper.selectByUsername(user.getUsername());
        //判断用户名是否存在，并判断密码
        if (u == null){
            return 3; //用户不存在
        }
        if (user.getPassword().equals(u.getPassword())){
            //把当前登录成功的用户信息保存在Session对象中
            session.setAttribute("u",u);
            return 1; //登录成功
        }
        return 2; //密码错误
    }

    @RequestMapping("/currentUser")
    public User currentUser(HttpSession session){
        return (User) session.getAttribute("u");
    }

    @RequestMapping("/logout")
    public void logout(HttpSession session){
        //删除登录成功时保存的用户对象
        session.removeAttribute("u");
    }
}
